package com.jsmile.cloud.authc.sys;

import java.util.List;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.jsmile.cloud.authc.api.req.sys.ReqSysRolePageQuery;
import com.jsmile.cloud.authc.api.req.sys.ReqSysRoleQuery;
import com.jsmile.cloud.authc.api.req.sys.ReqSysRoleUpdate;
import com.jsmile.cloud.authc.api.res.ResSysResources;
import com.jsmile.cloud.authc.api.res.ResSysRole;
import com.jsmile.cloud.authc.sys.model.SysRole;
import com.jsmile.cloud.authc.sys.repo.SysResourcesSearchRepository;
import com.jsmile.cloud.authc.sys.repo.SysRoleRepository;
import com.jsmile.cloud.authc.sys.repo.SysRoleSearchRepository;
import com.jsmile.mall.api.enums.SfEnum;
import com.jsmile.mall.api.exception.ExceptionKit;

import cn.hutool.core.bean.BeanUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@AllArgsConstructor
public class SysRoleApplicationService {

    private final SysRoleSearchRepository sysRoleSearchRepository;
    private final SysRoleRepository sysRoleRepository;
    private final SysResourcesSearchRepository sysResourcesSearchRepository;

    public IPage<ResSysRole> getPageList(ReqSysRolePageQuery reqSysRolePageQuery) {
        ExceptionKit.checkNotNull(reqSysRolePageQuery.getCurTenantId(), "租户id不能为空!");
        log.info("角色查询:{]", reqSysRolePageQuery);
        return sysRoleSearchRepository.pageQuery(reqSysRolePageQuery).convert(x -> BeanUtil.toBean(x, ResSysRole.class));
    }

    public List<ResSysResources> getMenuByRoles(ReqSysRoleQuery reqSysRoleQuery) {
        ExceptionKit.checkNotNull(reqSysRoleQuery.getCurTenantId(), "租户id不能为空!");
        log.info("角色查询:{]", reqSysRoleQuery);
        SysRole role = new SysRole();
        role.setId(reqSysRoleQuery.getRoleId());
        List<SysRole> roles = Lists.newArrayList(role);
        return sysResourcesSearchRepository.getMenuByRoleIds(null, roles, SfEnum.S.getValue());
    }

    public boolean saveRole(ReqSysRoleUpdate reqSysRoleUpdate) {
        return sysRoleRepository.save(SysRole.create(reqSysRoleUpdate));
    }

    public boolean saveRoleResources(ReqSysRoleUpdate reqSysRoleUpdate) {
        reqSysRoleUpdate.checkRoleResource();
        return sysRoleRepository.saveRoleResources(reqSysRoleUpdate.getRoleId(), reqSysRoleUpdate.getResourcesIds());
    }

    public boolean updateRole(ReqSysRoleUpdate reqSysRoleUpdate) {
        reqSysRoleUpdate.checkSuperAdmin();
        return sysRoleRepository.updateById(SysRole.create(reqSysRoleUpdate));
    }

    public boolean deleteRole(ReqSysRoleUpdate reqSysRoleUpdate) {
        reqSysRoleUpdate.checkSuperAdmin();
        return sysRoleRepository.removeById(reqSysRoleUpdate.getRoleId());
    }
}
